# -*- coding: utf-8 -*-
# @FileName : User.py
# @Time     : 2023/6/8 20:25
# @Author   : Zhong Runke
from application import app,db,r
from common.libs.webase.WebaseService import WebaseService
from web.controller.api import route_api
from flask import request, jsonify,make_response, g
from common.libs.user.UserService import UserService
from common.models.OauthMemberBind import OauthMemberBind
from common.models.User import User
from common.models.Wallet import Wallet
import ast, json
from common.libs.Helper import getCurrentDate
from common.libs.UrlManager import UrlManager
import datetime
from common.models.Address import Address


@route_api.route("/wechat/login", methods=["POST"])
def login():
    resp = {'code': 200, 'msg': 'OK', 'data': {}}
    req = request.values
    print(req)
    code = req['code'] if 'code' in req else ''
    if not code or len(code) < 1:
        resp['code'] = -1
        resp['msg'] = '需要code'
        return jsonify(resp)

    openid = UserService.getWeChatOpenId(code)
    print("openid", openid)
    print(type(openid))
    if openid is None:
        resp['code'] = -1
        resp['msg'] = '调用微信出错'
        return jsonify(resp)

    nickname = req['nickName'] if 'nickName' in req else ''
    gender = req['gender'] if 'gender' in req else 0
    avatar = req['avatarUrl'] if 'avatarUrl' in req else ''

    bind_info = OauthMemberBind.query.filter_by(openid = openid, type=1).first()
    if not bind_info:
        user_dict = WebaseService.createUser(openid)
        if not user_dict:
            resp['code'] = -1
            resp['msg'] = 'error'
            return resp
        print(type(user_dict))
        print(user_dict)
        webase_resp = WebaseService.commonReq(user_dict['address'], "register",
                                [openid, openid, "123456", "null", "null"],
                                app.config['WEBASE_CONTRACTABI'],
                                app.config['WEBASE_CONTRACTNAME'],
                                app.config['WEBASE_CONTRACTADDRESS'])
        webase_dict = json.loads(webase_resp)
        print(webase_dict)
        if webase_dict['message'] != 'Success':
            resp['code'] = -1
            resp['msg'] = '区块链异常'
            return jsonify(resp)
        model_user = User()
        model_user.avatar = avatar
        model_user.nickname = nickname
        model_user.login_pwd = "123456"
        model_user.login_salt = UserService.geneSalt()
        model_user.status = 1
        model_user.address = user_dict['address']
        model_user.blocknum = webase_dict['blockNumber']
        model_user.transactionhash = webase_dict['transactionHash']
        model_user.blockHash = webase_dict['blockHash']
        model_user.created_time = model_user.updated_time = getCurrentDate()
        db.session.add(model_user)
        db.session.commit()

        model_bind = OauthMemberBind()
        model_bind.openid = openid
        model_bind.user_id = model_user.id
        model_bind.client_type = 'wechat'
        model_bind.status = 1
        model_bind.type = 1
        model_bind.extra = ''
        model_bind.created_time = model_bind.updated_time = getCurrentDate()
        db.session.add(model_bind)
        db.session.commit()

        bind_info = model_bind
        print(webase_resp)
    user_info = User.query.filter_by(id=bind_info.user_id).first()
    print(user_info)
    token ="%s#%s" %(UserService.geneAuthCode(user_info), user_info.id)
    print(token)

    resp['data'] = {'token': token}
    return jsonify(resp)


@route_api.route("/wechat/check-reg", methods=["GET", "POST"])
def checkReg():
    resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
    req = request.values
    code = req['code'] if 'code' in req else ''
    if not code or len(code) < 1:
        resp['code'] = -1
        resp['msg'] = '需要code'
        return jsonify(resp)

    openid = UserService.getWeChatOpenId(code)
    if openid is None:
        resp['code'] = -2
        resp['msg'] = '调用微信错误，请重试'
        return jsonify(resp)

    bind_info = OauthMemberBind.query.filter_by(openid=openid, type=1).first()
    if not bind_info:
        resp['code'] = -1
        resp['msg'] = "未绑定"
        return jsonify(resp)

    user_info = User.query.filter_by( id = bind_info.user_id).first()
    if not user_info:
        resp['code'] = -1
        resp['msg'] = "未查询到绑定信息"
        return jsonify(resp)

    token = "%s#%s"%( UserService.geneAuthCode( user_info ),user_info.id )
    resp['data'] = { 'token':token }
    return jsonify(resp)


@route_api.route("/wechat/userinfo", methods=["GET", "POST"])
def getUserInfo():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    if request.method == 'GET':
        isAddressFlag = 0
        # 登录校验
        print("===============================================")
        auth_cookie = request.headers.get("Authorization") if 'Authorization' in request.headers else ''
        if not auth_cookie:
            resp['code'] = -1
            resp['msg'] = '没有Authorization'
            return jsonify(resp)
        print(auth_cookie)
        auth_info = auth_cookie.split("#")
        # 查询用户
        try:
            user_info = User.query.filter_by(id=auth_info[1]).first()
        except Exception as e:
            resp['code'] = -1
            resp['msg'] = '用户异常'
            return jsonify(resp)

        if not user_info:
            resp['code'] = -1
            resp['msg'] = '数据库查询错误'
            return jsonify(resp)
        # 查询用户是否有地址
        address_info = Address.query.filter_by(userAddress=user_info.address, is_default=1).first()
        if address_info:
            isAddressFlag = 1
        # 查询用户钱包
        wallet_info = Wallet.query.filter_by(useraddress=user_info.address).first()
        if wallet_info:
            wallet_msg = {
                'walletFlag': 1,
                'id': wallet_info.id,
                'name': wallet_info.name,
                'balance': wallet_info.balance,
                'blockHash': wallet_info.blockHash,
                'userAddress': wallet_info.useraddress
            }
        else:
            wallet_msg = {
                'walletFlag': 0
            }
        info = {
            'user_id': user_info.id,
            'avatar_url': UrlManager.buildImageUrl(user_info.avatar),
            'nickname': user_info.nickname,
            'gender_index': user_info.gender if user_info.gender != '' or user_info.gender is not None else 2,
            'birthday': user_info.birthday.strftime("%Y-%m-%d") if user_info.birthday else '2023-06-09',
            'mobile': user_info.mobile if user_info.mobile else '',
            'address': user_info.address,
            'isAddressFlag': isAddressFlag
        }
        resp['data']['info'] = info
        resp['data']['wallet_info'] = wallet_msg
        return jsonify(resp)
    elif request.method == "POST":
        req = request.values
        print(req)
        return jsonify(resp)


@route_api.route("/wechat/changeuserinfo")
def changeUserInfo():
    resp = {'code': 200, 'msg': 'OK', 'data': {}}
    auth_cookie = request.headers.get("Authorization")
    print(auth_cookie)
    auth_info = auth_cookie.split("#")
    try:
        user_info = User.query.filter_by(id=auth_info[1]).first()
    except Exception as e:
        print(e)
        resp['code'] = -1
        resp['msg'] = '用户异常'
        return jsonify(resp)

    if not user_info:
        resp['code'] = -1
        resp['msg'] = '数据库查询错误'
        return jsonify(resp)

    req = request.values
    print(req)
    info = req['info'] if 'info' in req else ''
    info_dict = json.loads(info)
    user_info.nickname = info_dict['nickname']
    user_info.gender = info_dict['gender_index']
    user_info.birthday = info_dict['birthday']
    user_info.mobile = info_dict['mobile']
    try:
        db.session.add(user_info)
        db.session.commit()
    except:
        resp['code'] = -1
        resp['msg'] = '数据库错误'
        return jsonify(resp)
    return jsonify(resp)


# 创建钱包信息
@route_api.route("/wechat/createWallet", methods=['GET', 'POST'])
def createWallet():
    resp = {'code':200, 'msg':'OK', 'data':{}}
    req = request.values
    print("--------------------------------")
    print(req)
    walletName = req['walletName'] if 'walletName' in req else ''
    user_id = int(req['user_id']) if 'user_id' in req else ''
    userAddress = req['userAddress'] if 'userAddress' in req else ''
    if walletName is None or len(walletName)<1:
        resp['code'] = -1
        resp['msg'] = '参数错误'
        return jsonify(resp)
    if user_id < 1:
        resp['code'] = -2
        resp['msg'] = '参数错误'
        return jsonify(resp)
    if userAddress is None or len(userAddress) < 5:
        resp['code'] = -3
        resp['msg'] = '参数错误'
        return jsonify(resp)

    wallet_info = Wallet.query.filter_by(useraddress=userAddress).first()
    if wallet_info:
        resp['code'] = -4
        resp['msg'] = '已创建钱包'
        return jsonify(resp)
    # 创建钱包 webase
    webase_resp = WebaseService.commonReq(userAddress, "createWallet",
                                          [walletName],
                                          app.config['WEBASE_CONTRACTABI'],
                                          app.config['WEBASE_CONTRACTNAME'],
                                          app.config['WEBASE_CONTRACTADDRESS'])
    webase_dict = json.loads(webase_resp)
    # 将数据存进数据库
    if webase_dict:
        model_wallet = Wallet()
        model_wallet.name = walletName
        model_wallet.balance = 0.00
        model_wallet.useraddress = userAddress
        model_wallet.blocknum = webase_dict['blockNumber']
        model_wallet.transactionhash = webase_dict['transactionHash']
        model_wallet.blockHash = webase_dict['blockHash']
        model_wallet.created_time = model_wallet.updated_time = getCurrentDate()
        try:
            db.session.add(model_wallet)
            db.session.commit()
        except:
            resp['code'] = -1
            resp['msg'] = '创建钱包失败'
            return jsonify(resp)
    else:
        resp['code'] = -1
        resp['msg'] = '创建钱包失败'
        return jsonify(resp)
    # 返回创建成功标记
    resp['data']['walletFlag'] = 1
    return jsonify(resp)


@route_api.route("/wechat/walletInfo", methods=["GET", "POST"])
def walletInfo():
    resp = {'code':200, 'msg':'OK', 'data':{}}
    if request.method == "GET":
        # 获取钱包信息
        req = request.values
        print("--------------------------------")
        print(req)
        user_id = int(req['user_id']) if 'user_id' in req else ''
        userAddress = req['userAddress'] if 'userAddress' in req else ''
        if user_id < 1:
            resp['code'] = -2
            resp['msg'] = '参数错误'
            return jsonify(resp)
        if userAddress is None or len(userAddress) < 5:
            resp['code'] = -3
            resp['msg'] = '参数错误'
            return jsonify(resp)

        wallet_info = Wallet.query.filter_by(useraddress=userAddress).first()
        if not wallet_info:
            resp['code'] = -1
            resp['msg'] = '数据库查询异常'
            return jsonify(resp)
        resp['data']['wallet_info'] = wallet_info.to_json()
        resp['data']['wallet_info']['created_time'] = wallet_info.created_time.strftime("%Y-%m-%d %H:%M:%S")
        return jsonify(resp)

    elif request.method == "POST":
        req = request.values
        print("--------------------------------")
        print(req)
        walletName = req['walletName'] if 'walletName' in req else ''
        user_id = int(req['user_id']) if 'user_id' in req else ''
        userAddress = req['userAddress'] if 'userAddress' in req else ''
        if walletName is None or len(walletName) < 1:
            resp['code'] = -1
            resp['msg'] = '参数错误'
            return jsonify(resp)
        if user_id < 1:
            resp['code'] = -2
            resp['msg'] = '参数错误'
            return jsonify(resp)
        if userAddress is None or len(userAddress) < 5:
            resp['code'] = -3
            resp['msg'] = '参数错误'
            return jsonify(resp)
        wallet_info = Wallet.query.filter_by(useraddress=userAddress).first()
        if not wallet_info:
            resp['code'] = -4
            resp['msg'] = '未创建钱包'
            return jsonify(resp)
        # 修改钱包信息
        webase_resp = WebaseService.commonReq(userAddress, "modifiyName",
                                              [walletName],
                                              app.config['WEBASE_CONTRACTABI'],
                                              app.config['WEBASE_CONTRACTNAME'],
                                              app.config['WEBASE_CONTRACTADDRESS'])
        webase_dict = json.loads(webase_resp)

        # 将数据存进数据库
        if webase_dict:
            wallet_info.name = walletName
            db.session.add(wallet_info)
            db.session.commit()
        else:
            resp['code'] = -5
            resp['msg'] = '访问区块链异常'
            return jsonify(resp)
        return jsonify(resp)
